<template>
  <div class="cyber-container cyber-filter">
    <div class="particles" id="particles"></div>

    <div class="container">
      <header class="neon-border">
        <h1>应用管理</h1>
        <div class="subtitle">用户问题文本聚类系统</div>
      </header>

      <div class="controls">
        <div class="layout-controls">
          <div class="control-group">
            <label for="cols">列数:</label>
            <input
                type="number"
                id="cols"
                v-model.number="cols"
                min="1"
                max="6"
            >
          </div>
          <div class="control-group">
            <label for="rows">行数:</label>
            <input
                type="number"
                id="rows"
                v-model.number="rows"
                min="1"
                max="10"
            >
          </div>
        </div>
        <div class="buttons">
          <button
              id="createBtn"
              class="pulse"
              @click="showCreateModal"
          >
            创建应用
          </button>
        </div>
      </div>

      <div class="status-bar">
        <div class="selected-count">已选择: {{ selectedApps.length }} 个应用</div>
        <button
            class="delete-selected-btn"
            :disabled="selectedApps.length === 0"
            @click="deleteSelectedApps"
        >
          删除选中
        </button>
      </div>

      <div class="app-grid-container" ref="gridContainerRef">
        <div class="app-grid" :style="{ gridTemplateColumns: `repeat(${cols}, 1fr)` }">
          <div
              v-for="app in apps"
              :key="app.app_id"
              class="app-card"
              :class="{ selected: selectedApps.includes(app.app_id) }"
              @click="toggleSelection(app.app_id)"
          >
            <div class="checkbox">
              <input
                  type="checkbox"
                  :id="`check-${app.app_id}`"
                  :data-id="app.app_id"
                  :checked="selectedApps.includes(app.app_id)"
                  @change="toggleSelection(app.app_id, $event.target.checked)"
              >
            </div>
            <a :href="`/clusters/${app.app_id}`" class="app-id">{{ app.app_id }}</a>
            <div class="app-name">{{ app.app_name }}</div>
            <div class="app-description">{{ app.app_description }}</div>
            <button
                class="delete-btn"
                @click.stop="showDeleteConfirm([app.app_id])"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建应用模态框 -->
    <div
        class="modal"
        :class="{ active: isCreateModalVisible }"
        @click="closeCreateModal"
    >
      <div class="modal-content" @click.stop>
        <h2 class="modal-title">创建应用</h2>
        <div class="form-group">
          <label for="appName">应用名称</label>
          <input
              type="text"
              id="appName"
              v-model="newAppName"
              placeholder="Enter application name"
          >
        </div>
        <div class="form-group">
          <label for="appDescription">应用描述</label>
          <textarea
              id="appDescription"
              v-model="newAppDescription"
              placeholder="Enter application description"
          ></textarea>
        </div>
        <div class="form-group">
          <label>上传数据文件 (.txt)</label>
          <div class="file-upload">
            <input
                type="file"
                id="appFile"
                accept=".txt"
                @change="handleFileChange"
            >
            <label class="file-upload-label" for="appFile">
              点击选择TXT文件或拖拽文件到此处
            </label>
            <div class="file-info" :style="{ color: fileError ? '#ff6666' : '#00eeff' }">
              {{ fileInfo }}
            </div>
          </div>
        </div>
        <div class="modal-buttons">
          <button @click="closeCreateModal">取消</button>
          <button @click="createApp" :disabled="!canCreateApp">创建</button>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div
        class="confirm-modal"
        :class="{ active: isConfirmModalVisible }"
        @click="closeConfirmModal"
    >
      <div class="modal-content" @click.stop>
        <h2 class="modal-title">确认删除</h2>
        <p>{{ confirmText }}</p>
        <div class="modal-buttons">
          <button @click="closeConfirmModal">取消</button>
          <button
              @click="confirmDelete"
              style="background: linear-gradient(45deg, #cc0066, #ff0066); border-color: #ff0066; color: white;"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div
        v-if="isLoading"
        class="loading-overlay"
    >
      <div class="spinner"></div>
    </div>
  </div>

  <Notification ref="notification"></Notification>
</template>

<script setup>
import Notification from "@/components/Notification.vue";
import {ref, computed, onMounted, onUnmounted, watch} from 'vue'
import {useRouter} from 'vue-router'

const router = useRouter()

// 响应式数据
const apps = ref([
  {
    app_id: 'CLSTR-001',
    app_name: 'Neural Text Analyzer',
    app_description: 'Advanced clustering algorithm for semantic text analysis with real-time processing capabilities.'
  }
])

const selectedApps = ref([])
const cols = ref(3)
const rows = ref(3)
const isCreateModalVisible = ref(false)
const isConfirmModalVisible = ref(false)
const isLoading = ref(false)
const newAppName = ref('')
const newAppDescription = ref('')
const uploadedFile = ref(null)
const fileError = ref(false)
const appsToDelete = ref([])
const notification = ref(null)

// DOM 引用
const gridContainerRef = ref(null)

// 计算属性
const fileInfo = computed(() => {
  if (fileError.value) {
    return '错误：只支持 .txt 文件'
  }
  if (uploadedFile.value) {
    return `已选择: ${uploadedFile.value.name} (${(uploadedFile.value.size / 1024).toFixed(2)} KB)`
  }
  return '未选择文件'
})

const canCreateApp = computed(() => {
  return newAppName.value.trim() !== '' &&
      newAppDescription.value.trim() !== '' &&
      uploadedFile.value !== null &&
      !fileError.value
})

const confirmText = computed(() => {
  if (appsToDelete.value.length === 1) {
    const app = apps.value.find(app => app.app_id === appsToDelete.value[0])
    return `确定要删除应用 "${app?.name}" 吗？此操作不可撤销。`
  } else {
    return `确定要删除选中的 ${appsToDelete.value.length} 个应用吗？此操作不可撤销。`
  }
})

// 方法
function createParticles() {
  const particlesContainer = document.getElementById('particles');
  particlesContainer.innerHTML = '';

  for (let i = 0; i < 30; i++) {
    const particle = document.createElement('div');
    particle.className = 'particle';

    // 随机大小和颜色
    const size = Math.random() * 10 + 2;
    const colors = [
      'rgba(0, 238, 255, 0.6)',
      'rgba(0, 255, 157, 0.6)',
      'rgba(255, 0, 230, 0.6)',
      'rgba(100, 200, 255, 0.6)'
    ];

    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;
    particle.style.background = colors[Math.floor(Math.random() * colors.length)];

    // 随机位置
    particle.style.left = `${Math.random() * 100}%`;
    particle.style.top = `${Math.random() * 100}%`;

    // 随机动画延迟
    particle.style.animationDelay = `${Math.random() * 5}s`;

    particlesContainer.appendChild(particle);
  }
}

const toggleSelection = (appId, checked) => {
  const isChecked = checked !== undefined ? checked : !selectedApps.value.includes(appId)

  if (isChecked && !selectedApps.value.includes(appId)) {
    selectedApps.value.push(appId)
  } else if (!isChecked) {
    selectedApps.value = selectedApps.value.filter(id => id !== appId)
  }
}

const showCreateModal = () => {
  newAppName.value = ''
  newAppDescription.value = ''
  uploadedFile.value = null
  fileError.value = false
  isCreateModalVisible.value = true
}

const closeCreateModal = () => {
  isCreateModalVisible.value = false
}

const showDeleteConfirm = (appIds) => {
  appsToDelete.value = appIds
  isConfirmModalVisible.value = true
}

const closeConfirmModal = () => {
  isConfirmModalVisible.value = false
  appsToDelete.value = []
}

const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.name.toLowerCase().endsWith('.txt')) {
      uploadedFile.value = file
      fileError.value = false
    } else {
      fileError.value = true
      uploadedFile.value = null
    }
  }
}

const createApp = async () => {
  if (!canCreateApp.value) return

  isLoading.value = true

  try {
    // 模拟创建过程（包括文件上传）
    await new Promise(resolve => setTimeout(resolve, 2500))
    const formData = new FormData()
    formData.append('app_name', newAppName.value)
    formData.append('app_description', newAppDescription.value)
    formData.append('file', uploadedFile.value)

    const response = await fetch('http://localhost:5000/apps/create', {
      method: 'POST',
      body: formData
    })

    const data = await response.json()
    if (data.error) {
      notification.value.showNotificationMessage(data.error, 'error')
    }

    // 添加新应用
    apps.value.push({
      app_id: data["app_id"],
      app_name: newAppName.value.trim(),
      app_description: newAppDescription.value.trim(),
      fileName: uploadedFile.value.name,
      fileSize: uploadedFile.value.size
    })

    closeCreateModal()
    notification.value.showNotificationMessage('应用创建成功！！！', 'success')
  } catch (error) {
    notification.value.showNotificationMessage('error', 'error')
  } finally {
    isLoading.value = false
  }
}

const deleteApp = async (appIds) => {
  isLoading.value = true

  try {
    // 模拟删除过程
    // await new Promise(resolve => setTimeout(resolve, 1500))
    const response = await fetch("http://localhost:5000/apps/delete-batch", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_ids: appIds
      })
    })

    const data = await response.json()
    if (data.error) {
      notification.value.showNotificationMessage(data.error, 'error')
    } else {
      notification.value.showNotificationMessage('应用已删除！！！', 'success')
    }

    // 删除应用
    apps.value = apps.value.filter(app => !appIds.includes(app.app_id))

    // 清除选中状态
    selectedApps.value = selectedApps.value.filter(id => !appIds.includes(id))
  } catch (error) {
    notification.value.showNotificationMessage('error', 'error')
  } finally {
    isLoading.value = false
  }
}

const confirmDelete = async () => {
  await deleteApp(appsToDelete.value)
  closeConfirmModal()
}

const deleteSelectedApps = () => {
  if (selectedApps.value.length > 0) {
    showDeleteConfirm([...selectedApps.value])
  }
}

// 监听器
watch(cols, () => {
  // 列数变化时可能需要重新调整布局
})

watch(rows, () => {
  if (gridContainerRef.value) {
    gridContainerRef.value.style.height = `${rows.value * 220}px`
  }
})

// 键盘事件处理
const handleKeyDown = (event) => {
  if (event.key === 'Escape') {
    closeCreateModal()
    closeConfirmModal()
  }
}

// 生命周期钩子
onMounted(async () => {
  if (localStorage.getItem('isLoggedIn') !== 'true') {
    router.replace('/login')
  }

  createParticles()

  // 设置初始容器高度
  if (gridContainerRef.value) {
    gridContainerRef.value.style.height = `${rows.value * 220}px`
  }

  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown)

  // 添加窗口大小变化监听
  window.addEventListener('resize', createParticles)

  try {
    const response = await fetch(
        "http://localhost:5000/apps/list",
    )
    const result = await response.json()
    if (result.error) {
      notification.value.showNotificationMessage(result.error, 'error')
    } else {
      apps.value = result.apps
    }
  } catch (error) {
    console.log(error)
    notification.value.showNotificationMessage(error, 'error')
  }
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('resize', createParticles)
})
</script>

<style src="@/assets/styles/cluster-list.css"></style>
